

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include "rtde_socket.h"
#include <netinet/tcp.h>



int socket_connect(const char* host, int port)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        printf("client socket creation failed with %s:%d", host, port);
        return -1;
    }

    int syncnt = 2;
    setsockopt(sockfd, IPPROTO_TCP, TCP_SYNCNT, &syncnt, sizeof(syncnt));

    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(port);
    if (inet_aton(host, &serv_addr.sin_addr) == 0) {
        printf("client inet_aton failed with [%d]%s", errno, strerror(errno));
        return -1;
    }

    if (connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
        printf("client connect failed with [%d]%s", errno, strerror(errno));
        return -1;
    }

    return sockfd;
}

int socket_send(int sockfd, const void* buf, int len)
{
    int wsize = send(sockfd, buf, len,0);
    if (wsize < 0) {
        printf("client send failed with [%d]%s", errno, strerror(errno));
        return -1;
    }
    return wsize;
}

int socket_recv(int sockfd, void* buf)
{
    // code to receive data over a socket
    int rsize = recv(sockfd, buf, SOCKET_RECEIVE_LEN, 0);
    if (rsize < 0) {
        printf("client recv failed with [%d]%s", errno, strerror(errno));
        return -1;
    }
    return rsize;
}

int socket_close(int sockfd)
{
    return close(sockfd);
}

